const express = require("express")
const router = express.Router()
const multer = require('multer')
const path = require("path")
const jimp = require("jimp")

async function mack(
    waterFile,
    originFile,
    targetFile,
    proportion = 5, //默认比例
    marginProportion = 0.01, //边距
    opacitySource = 0.3
) {
    const [origin, water] = await Promise.all([jimp.read(originFile), jimp.read(waterFile)])

    // 对水印图片进行缩放
    const curProportion = origin.bitmap.width / water.bitmap.width; //当前比例 = 图片宽度 / 水印宽度
    water.scale(curProportion / proportion) // 缩放倍数 = 当前比例 / 目标比例

    // 计算位置
    const right = origin.bitmap.width * marginProportion;
    const bottom = origin.bitmap.height * marginProportion;
    const x = origin.bitmap.width - right - water.bitmap.width;
    const y = origin.bitmap.height - bottom - water.bitmap.height;

    origin.composite(water, x, y, {
        mode: jimp.BLEND_SOURCE_OVER, //设置模式  
        opacitySource // 透明度
    })

    await origin.write(targetFile)
}
const storage = multer.diskStorage({
    destination: function (req, file, cb) { //保存文件的线上地址
        cb(null, path.resolve(__dirname, "../../public/upload"))
    },
    filename: function (req, file, cb) { //
        // 时间戳 + 随机字符6 + 文件后缀名
        const timeSteap = Date.now()
        const randomStr = Math.random().toString(32).slice(-6)
        const ext = path.extname(file.originalname)
        const filename = `${timeSteap}-${randomStr}${ext}`
        // console.log(file)
        cb(null, filename)
    }
})

function fileFilter(req, file, cb) {

    const whiteList = [".jpg", ".png", ".webp"];
    const ext = path.extname(file.originalname)
    if (whiteList.includes(ext)) {
        // 接受这个文件，使用`true`，像这样:
        cb(null, true)
    } else {
        cb(new Error(`you ext name of ${ext} is no support`))
    }
}

const upload = multer({
    storage, //在哪里存储文件
    limits: { //限制上传的数据
        fileSize: 7000 * 1024
    },
    fileFilter
})

const waterPath = path.resolve(__dirname, "../../public/images/shuiyin.png")
router.post("/", upload.single('img'), async(req, res) => {
    const newPath = path.resolve(__dirname, "../../public/shuiyinimg", req.file.filename)
    await mack(waterPath, req.file.path, newPath)
    const originurl = `/upload/${req.file.filename}`;
    const waterurl = `/shuiyinimg/${req.file.filename}`
    res.send({
        code: 0,
        msg: "",
        data: {
            originurl,
            waterurl
        }
    })
})

module.exports = router